package com.vcar.LDiceServer.filter;

import java.io.ByteArrayOutputStream;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import flex.messaging.io.SerializationContext;
import flex.messaging.io.amf.Amf3Output;

public class AMF3Encoder implements ProtocolEncoder
{
    private final SerializationContext context = new SerializationContext();
    private final Amf3Output	   amf3out;

    public AMF3Encoder()
    {
	amf3out = new Amf3Output(context);
    }

    public void dispose(IoSession session) throws Exception
    {
	amf3out.close();
    }

    public void encode(IoSession session, Object message,
	    ProtocolEncoderOutput out) throws Exception
    {
	IoBuffer buffer;
	ByteArrayOutputStream stream = new ByteArrayOutputStream();
	amf3out.setOutputStream(stream);
	amf3out.write(new byte[4]);
	amf3out.writeObject(message);
	amf3out.flush();
	byte bytes[] = stream.toByteArray();
	int size = bytes.length;
	bytes[0] = (byte) ((size >> 0) & 255);
	bytes[1] = (byte) ((size >> 8) & 255);
	bytes[2] = (byte) ((size >> 16) & 255);
	bytes[3] = (byte) ((size >> 24) & 255);
	buffer = IoBuffer.allocate(bytes.length, false);
	buffer.put(bytes);
	buffer.flip();
	out.write(buffer);
	buffer.free();
    }
}
